import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { X, Code, Database, ChevronRight, Copy, Check } from 'lucide-react';
import { useAppStore } from '@/stores/appStore';

interface DataFlowDrawerProps {
  isOpen: boolean;
  onClose: () => void;
}

interface StageData {
  id: string;
  name: string;
  description: string;
  data: any;
  status: 'completed' | 'current' | 'pending';
}

export function DataFlowDrawer({ isOpen, onClose }: DataFlowDrawerProps) {
  const { zkProofData, blockchainTx } = useAppStore();
  const [copiedItem, setCopiedItem] = useState<string>('');

  const copyToClipboard = async (text: string, itemId: string) => {
    try {
      await navigator.clipboard.writeText(text);
      setCopiedItem(itemId);
      setTimeout(() => setCopiedItem(''), 2000);
    } catch (error) {
      console.error('Failed to copy to clipboard:', error);
    }
  };

  const stageDataFlow: StageData[] = [
    {
      id: 'stage1',
      name: '阶段1: 输入数据',
      description: '用户输入的原始数据和生成的Poseidon哈希',
      status: 'completed',
      data: {
        preImage: zkProofData?.input?.preImage || '',
        dataHash: zkProofData?.input?.dataHash || '',
        timestamp: zkProofData?.metadata?.generatedAt || ''
      }
    },
    {
      id: 'stage2',
      name: '阶段2: 证明生成',
      description: '零知识证明数据和公共信号',
      status: 'completed',
      data: {
        proof: zkProofData?.proof || {},
        publicSignals: zkProofData?.public || [],
        algorithm: zkProofData?.metadata?.algorithm || 'PLONK',
        isSimulated: zkProofData?.metadata?.isSimulated || false
      }
    },
    {
      id: 'stage3',
      name: '阶段3: ABI编码',
      description: '为区块链调用编码的参数',
      status: 'completed',
      data: {
        methodName: 'verifyAssetZKPacked',
        packedProof: (() => {
          try {
            if (zkProofData?.proof) {
              const proofString = JSON.stringify(zkProofData.proof);
              if (typeof proofString === 'string' && proofString.length > 100) {
                return '0x' + proofString.slice(0, 100) + '...';
              }
              return '0x' + proofString;
            }
            return '';
          } catch (error) {
            console.warn('Error stringifying proof data:', error);
            return 'Error: Invalid proof data';
          }
        })(),
        dataHash: zkProofData?.input?.dataHash || '',
        gasLimit: '300000'
      }
    },
    {
      id: 'stage4',
      name: '阶段4: 区块链调用',
      description: '发送到区块链的交易数据和响应',
      status: blockchainTx ? 'completed' : 'current',
      data: blockchainTx || {
        status: 'pending',
        message: '等待区块链调用...'
      }
    }
  ];

  const formatJson = (obj: any) => {
    try {
      return JSON.stringify(obj, null, 2);
    } catch {
      return String(obj);
    }
  };

  return (
    <AnimatePresence>
      {isOpen && (
        <>
          {/* Backdrop */}
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/50 z-40"
            onClick={onClose}
          />

          {/* Drawer */}
          <motion.div
            initial={{ x: '100%' }}
            animate={{ x: 0 }}
            exit={{ x: '100%' }}
            transition={{ type: 'spring', damping: 30, stiffness: 300 }}
            className="fixed right-0 top-0 h-full w-full max-w-2xl bg-slate-900 border-l border-slate-700 z-50 flex flex-col"
          >
            {/* Header */}
            <div className="flex items-center justify-between p-6 border-b border-slate-700">
              <div className="flex items-center space-x-3">
                <Database className="w-6 h-6 text-quantum-blue" />
                <div>
                  <h2 className="text-xl font-bold text-white">数据流监控</h2>
                  <p className="text-sm text-gray-400">每个阶段的输入输出数据</p>
                </div>
              </div>
              <button
                onClick={onClose}
                className="p-2 hover:bg-slate-800 rounded-lg transition-colors"
              >
                <X className="w-5 h-5 text-gray-400" />
              </button>
            </div>

            {/* Content */}
            <div className="flex-1 overflow-y-auto p-6 space-y-6">
              {stageDataFlow.map((stage, index) => (
                <motion.div
                  key={stage.id}
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: index * 0.1 }}
                  className={`border rounded-lg p-4 ${
                    stage.status === 'completed'
                      ? 'border-crypto-green bg-crypto-green/5'
                      : stage.status === 'current'
                      ? 'border-quantum-blue bg-quantum-blue/5'
                      : 'border-gray-600 bg-gray-700/20'
                  }`}
                >
                  {/* Stage Header */}
                  <div className="flex items-center justify-between mb-3">
                    <div className="flex items-center space-x-3">
                      <div className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold ${
                        stage.status === 'completed'
                          ? 'bg-crypto-green text-black'
                          : stage.status === 'current'
                          ? 'bg-quantum-blue text-white'
                          : 'bg-gray-600 text-gray-300'
                      }`}>
                        {index + 1}
                      </div>
                      <div>
                        <h3 className="font-semibold text-white">{stage.name}</h3>
                        <p className="text-sm text-gray-400">{stage.description}</p>
                      </div>
                    </div>
                    <div className={`px-2 py-1 rounded text-xs font-medium ${
                      stage.status === 'completed'
                        ? 'bg-crypto-green/20 text-crypto-green'
                        : stage.status === 'current'
                        ? 'bg-quantum-blue/20 text-quantum-blue'
                        : 'bg-gray-600/20 text-gray-400'
                    }`}>
                      {stage.status === 'completed' ? '✓ 完成' : 
                       stage.status === 'current' ? '⚡ 进行中' : '⏳ 等待'}
                    </div>
                  </div>

                  {/* Data Display */}
                  <div className="space-y-3">
                    {Object.entries(stage.data).map(([key, value]) => (
                      <div key={key} className="bg-slate-800 rounded p-3">
                        <div className="flex items-center justify-between mb-2">
                          <span className="text-sm font-medium text-gray-300 capitalize">
                            {key.replace(/([A-Z])/g, ' $1').trim()}
                          </span>
                          <button
                            onClick={() => copyToClipboard(formatJson(value), `${stage.id}-${key}`)}
                            className="p-1 hover:bg-slate-700 rounded transition-colors"
                          >
                            {copiedItem === `${stage.id}-${key}` ? (
                              <Check className="w-4 h-4 text-crypto-green" />
                            ) : (
                              <Copy className="w-4 h-4 text-gray-400" />
                            )}
                          </button>
                        </div>
                        
                        <div className="text-xs text-gray-300 font-mono bg-slate-900 rounded p-2 max-h-32 overflow-y-auto">
                          {typeof value === 'object' ? (
                            <pre className="whitespace-pre-wrap break-all">
                              {formatJson(value)}
                            </pre>
                          ) : (
                            <span className="break-all">
                              {String(value) || 'N/A'}
                            </span>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>

                  {/* Flow Arrow */}
                  {index < stageDataFlow.length - 1 && (
                    <div className="flex justify-center mt-4">
                      <ChevronRight className="w-5 h-5 text-gray-500" />
                    </div>
                  )}
                </motion.div>
              ))}
            </div>

            {/* Footer */}
            <div className="p-6 border-t border-slate-700">
              <div className="flex items-center justify-between text-sm text-gray-400">
                <div className="flex items-center space-x-2">
                  <Code className="w-4 h-4" />
                  <span>开发者模式数据流</span>
                </div>
                <div>
                  最后更新: {new Date().toLocaleTimeString()}
                </div>
              </div>
            </div>
          </motion.div>
        </>
      )}
    </AnimatePresence>
  );
}